/**
 * Created by lwk on 2019/1/23.
 */
import axios from 'axios'
import util from './util'
import { Toast } from 'mand-mobile'

/**
 * 默认请求参数
 * @type {{url: string, param: {}, showLoading: boolean, showMessage: boolean, loadingText: string, method: string, timeout: number}}
 * @private
 */
const _defaultOption = {
  url: '',
  param: {},
  showLoading: true,
  showMessage: true,
  loadingText: '加载中',
  method: 'get',
  timeout: 60000
}

/**
 * 发起请求
 * @param option
 * @returns {*}
 * @private
 */
let _httpRequest = (option = {}) => {
  let finalOption = Object.assign(_defaultOption, option)
  let method = finalOption.method.toLowerCase()
  let config = {
    method: method,
    url: finalOption.url,
    timeout: finalOption.timeout
  }

  if ('get' === method) {
    config['params'] = finalOption.param
  } else if ('post' === method) {
    config['data'] = finalOption.param
    config['headers'] = {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
    config['transformRequest'] = [function (data) {
      let result = []
      for (let key in data) {
        let value = data[key] || data[key] === 0 ? data[key] : ''
        result.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
      }
      return result.join('&')
    }]
  }
  return axios.request(config)
}

/**
 * 处理返回结果
 * @param option
 * @returns {Promise<any>}
 * @private
 */
let _handleResult = (option = {}) => {
  let finalOption = Object.assign(_defaultOption, option)
  let { showLoading, showMessage, loadingText } = finalOption

  // 是否显示加载提示框
  showLoading && _showLoading(loadingText, 0)

  return new Promise((resolve, reject) => {
    _httpRequest(option).then(res => {

      // 隐藏提示框
      _hideToast()

      let result = res.data
      let message = result.message
      let code = result.code
      let success = result.success ? result.success : (code === 200 ? true : false)

      // 返回响应结果
      if (showMessage && util.isNotBlank(message)) {
        _showMessage(message, success, () => {
          resolve(result)
        })
      } else {
        resolve(result)
      }
    }).catch(e => {
      _hideLoading()
      reject(e)
    })
  })
}

/**
 * 显示加载提示框
 * @param content 内容
 * @param duration 时长
 * @private
 */
let _showLoading = (content, duration = 3000) => {
  Toast.loading(content, duration)
}

/**
 * 显示消息提示框
 * @param content 内容
 * @param isSuccess 结果
 * @param onClose 信息关闭回调
 * @private
 */
let _showMessage = (content, isSuccess, onClose) => {
  if (isSuccess) {
    Toast.succeed(content)
  } else {
    Toast.failed(content)
  }
  setTimeout(() => {
    onClose()
  }, 3000)
}

/**
 * 隐藏提示框
 * @private
 */
let _hideToast = () => {
  Toast.hide()
}

/**
 * GET请求
 * @param option
 */
let get = (option = {}) => {
  option['method'] = 'get'
  return _handleResult(option)
}

/**
 * POST请求
 * @param option
 */
let post = (option = {}) => {
  option['method'] = 'post'
  return _handleResult(option)
}

export default {
  get,
  post
}
